package com.example.its2021606134chh.BusModule;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.MainActivity;
import com.example.its2021606134chh.R;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BusLineFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BusLineFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TextView tvBusLineMap;
    private EditText edtBusLineNum;
    private TextView tvBusLineSearch;
    private RecyclerView rvBusLineList;
    private TextView tvBusLineClear;
    private List<rvBusLineData> list = new ArrayList<>();
    private String busline_name;
    private String start_place;
    private String end_place;
    BusHistorySQLiteOpenHelper historyOpenHelper;
    SQLiteDatabase database2;
    boolean isCreated;

    public BusLineFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BusLineFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BusLineFragment newInstance(String param1, String param2) {
        BusLineFragment fragment = new BusLineFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bus_line, container, false);
        tvBusLineMap = (TextView) view.findViewById(R.id.tvBusLineMap);
        edtBusLineNum = (EditText) view.findViewById(R.id.edtBusLineNum);
        tvBusLineSearch = (TextView) view.findViewById(R.id.tvBusLineSearch);
        rvBusLineList = (RecyclerView) view.findViewById(R.id.rvBusLineList);
        tvBusLineClear = (TextView) view.findViewById(R.id.tvBusLineClear);
        tvBusLineMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {   //打开离线地图类（未写）
                Intent intent = new Intent(getContext(), MainActivity.class);
                startActivity(intent);
                Objects.requireNonNull(getActivity()).finish();
            }
        });
        tvBusLineSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String busNum = edtBusLineNum.getText().toString().trim();
                if (!busNum.equals("")) {
                    Intent intent = new Intent(getContext(), BusLineActivity.class);
                    intent.putExtra("BusLineNum", busNum);
                    startActivity(intent);
                } else {
                    Toast.makeText(getContext(), "搜索内容不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        SharedPreferences sp;
        sp = getActivity().getSharedPreferences("BusLineHistory", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        int x = sp.getInt("BusF1",1);
        if (x == 1)
        {
            x++;
            editor.putInt("BusF1",x);
            editor.commit();
        } else {
            //        通过数据库读取记录
            historyOpenHelper = new BusHistorySQLiteOpenHelper(getContext(), "bushistory.db", null, 1);
            database2 = historyOpenHelper.getReadableDatabase();
            try (Cursor cursor = database2.query("bushistory", null, null, null, null, null, null)) {
                if (cursor.moveToFirst()) {
                    do {
                        busline_name = cursor.getString(1);
                        start_place = cursor.getString(2);
                        end_place = cursor.getString(3);
                        list.add(new rvBusLineData(busline_name, start_place, end_place));
                        rvBusLineList.setLayoutManager(new LinearLayoutManager(getContext()));
                        rvBusLineList.setAdapter(new BusLineRViewAdapter(list));
                    } while (cursor.moveToNext());
                }
            } catch (SQLException ignored) {
                Toast.makeText(getContext(), "没有查询到历史数据！", Toast.LENGTH_SHORT).show();
            } finally {
                database2.close();
            }
            tvBusLineClear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                清空数据库
                    try {
                        database2 = historyOpenHelper.getWritableDatabase();
                        database2.delete("bushistory", "id > ?", new String[] { "0" });
//                        BusHistorySQLiteOpenHelper.dropDb(database2);
                        database2.close();
                        list.clear();
                        rvBusLineList.setAdapter(new BusLineRViewAdapter(list));
                        int x = sp.getInt("BusF1",1);
                        editor.putInt("BusF1",x);
                        editor.commit();
                        Toast.makeText(getContext(), "清空历史数据！", Toast.LENGTH_SHORT).show();
                    } catch (NullPointerException ignored) {
                        Toast.makeText(getContext(), "没有历史数据！", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        // Inflate the layout for this fragment
        return view;
    }

}